package com.example.llm.sgg.chat.handler;

import com.example.llm.sgg.chat.dto.ChatMessageDTO;
import org.springframework.data.redis.connection.ReactiveSubscription;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class RedisMessageSubPublisher {

    private final ReactiveRedisTemplate<String, ChatMessageDTO> reactiveRedisTemplate;

    public RedisMessageSubPublisher(ReactiveRedisTemplate<String, ChatMessageDTO> redisTemplate) {
        this.reactiveRedisTemplate = redisTemplate;
    }

    // 发布点对点消息
    public Mono<Long> publishToUser(String recipientId, ChatMessageDTO message) {
        String channel = "user::" + recipientId;
        return reactiveRedisTemplate.convertAndSend(channel, message);
    }

    // 发布系统广播消息
    public Mono<Long> publishBroadcast(ChatMessageDTO message) {
        return reactiveRedisTemplate.convertAndSend("system::broadcast", message);
    }

    // 订阅新消息
    public Flux<ChatMessageDTO> subscribeFromOther(String userId) {
        return reactiveRedisTemplate.listenToChannel("user::" + userId)
                .map(ReactiveSubscription.Message::getMessage);
    }

    // 订阅新消息
    public Flux<ChatMessageDTO> subscribeBroadcast() {
        return reactiveRedisTemplate.listenToChannel("system::broadcast")
                .map(ReactiveSubscription.Message::getMessage);
    }
}
